package cn.iocoder.yudao.module.trade.job.order;

import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.promotion.api.shortLinkDetail.ShortLinkDetailApi;
import cn.iocoder.yudao.module.trade.api.order.TradeOrderApi;
import cn.iocoder.yudao.module.trade.dal.dataobject.job.SmsParam;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.iocoder.yudao.module.trade.service.order.TradeOrderQueryService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 未支付订单的自动短信提醒 Job
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class TradeOrderAutoUnpaidJob implements JobHandler {

    @Resource
    private TradeOrderQueryService tradeOrderQueryService;

    @Resource
    private ShortLinkDetailApi shortLinkDetailApi;

    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    @Override
    @TenantJob
    public String execute(String param) {
        List<TradeOrderDO> orderDOList = tradeOrderQueryService.getOrderListByTime();
        for (TradeOrderDO tradeOrderDO : orderDOList) {
            sendSms(tradeOrderDO);
        }
        return String.format("过期订单 %s 个", 1);
    }

    public void sendSms(TradeOrderDO tradeOrderDO) {
        try {
            Map<String, Object> map = new HashMap<>();
            String appkey = "";
            String appsecret = "";
            String appcode = "";
            String operator = identifyOperator(tradeOrderDO.getReceiverMobile());
            if (operator.equals("中国移动")) {
                appkey = "900408";
                appsecret = "zmtegA";
                appcode = "1000";
            } else {
                appkey = "900409";
                appsecret = "858QLD";
                appcode = "1000";
            }
            map.put("appkey", appkey);
            map.put("appcode", appcode);
            String timestamp = System.currentTimeMillis() + "";
            map.put("timestamp", timestamp);
            List<SmsParam> smsParam = new ArrayList<>();
            SmsParam each = new SmsParam();
            String encodedData = URLEncoder.encode("{\"items\":[{\"skuId\":" + tradeOrderDO.getSkuId() + ",\"count\":" + tradeOrderDO.getCount() + ",\"categoryId\":" + tradeOrderDO.getCategoryId() + "}]}&preferentialRatio=" + tradeOrderDO.getPreferentialRatio(), "UTF-8");
            String longUrl = "https://www.zhangfkj.cn/pages/order/confirm?data=" + encodedData;
            String shortDomain = "8j4.cn";
            //生成短链
           String shortUrl =  shortLinkDetailApi.createShortLinkDetail(shortDomain, longUrl, Long.valueOf(tradeOrderDO.getReceiverMobile()));
            each.setMsg("【掌枫兑】亲爱的" + tradeOrderDO.getReceiverName() + "，您有一笔订单尚未支付，商品库存不多，点" + shortUrl + " 付款后优先安排发货！拒收请回复R");
            each.setExtend("");
            each.setPhone(tradeOrderDO.getReceiverMobile());
            smsParam.add(each);
            map.put("sms", smsParam);
            String sign = md5(appkey + appsecret + timestamp);
            map.put("sign", sign);
            String responseText = HttpUtil.post("http://101.37.35.20:9090/sms/distinct/v1", JsonUtils.toJsonString(map));
            log.info(responseText);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    public static String identifyOperator(String phoneNumber) {
        String operator = "未知运营商";
        // 中国移动
        if (phoneNumber.matches("^1(34|35|36|37|38|39|47|50|51|52|57|58|59|78|82|83|84|87|88|98)\\d{8}$")) {
            operator = "中国移动";
        }
        // 中国联通
        if (phoneNumber.matches("^1(30|31|32|55|56|85|86|45|76)\\d{8}$")) {
            operator = "中国联通";
        }
        // 中国电信
        if (phoneNumber.matches("^1(33|53|80|81|89|77|49|99)\\d{8}$")) {
            operator = "中国电信";
        }
        return operator;
    }

    private static String md5(String param) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] md5Byte = md5.digest(param.getBytes("utf8"));
        String result = byteToHex(md5Byte);
        return result;
    }

    private static String byteToHex(byte[] md5Byte) {
        String result = "";
        StringBuilder sb = new StringBuilder();
        for (byte each : md5Byte) {
            int value = each & 0xff;
            String hex = Integer.toHexString(value);
            if (value < 16) {
                sb.append("0");
            }
            sb.append(hex);
        }
        result = sb.toString();
        return result;
    }


    /**
     * 聚合数据短信接口
     *
     * @param tradeOrderDO
     */
    public static void mobileQuery(TradeOrderDO tradeOrderDO) {
        String result = null;
        String url = "http://v.juhe.cn/sms/send";//请求接口地址
        Map params = new HashMap();//请求参数
        params.put("mobile", tradeOrderDO.getReceiverMobile());//接受短信的用户手机号码
        params.put("tpl_id", 264786);//申请的短信模板ID，根据实际情况修改
        params.put("tpl_value", "#name=#" + tradeOrderDO.getReceiverName() + "&#url#=https://www.zhangfkj.cn/pages/order/detail?id=" + tradeOrderDO.getId());//设置的模板变量，根据实际情况修改
        params.put("key", "c7159e328b62f01f0022c91d936decc1");//应用APPKEY(应用详细页查询)
        try {
            result = net(url, params, "POST");
            JSONObject object = JSONObject.parseObject(result);
            if (object.get("error_code").equals(0)) {
                System.out.println(object.get("result"));
            } else {
                System.out.println(object.get("error_code") + ":" + object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return 网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    //将map型转为请求参数型
    public static String urlencode(Map<String, String> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
